<template>
	<view class="edit-profile">
		<!-- 头像 -->
		<view class="form-item">
			<text class="label">头像</text>
			<button
				class="avatar-wrapper"
				open-type="chooseAvatar"
				@chooseavatar="onChooseAvatar">
				<image
					class="avatar"
					:src="form.avatar"
					mode="aspectFill" />
			</button>
		</view>

		<!-- 昵称 -->
		<view class="form-item">
			<text class="label">昵称</text>
			<input
				class="input"
				v-model="form.username"
				placeholder="请输入昵称" />
		</view>

		<!-- 保存按钮 -->
		<button
			class="save-btn"
			@tap="handleSave">
			保存
		</button>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useUserStore } from '../../stores/user'
import { userApi } from '../../api/user'

const userStore = useUserStore()
const form = reactive({
	avatar: userStore.userInfo?.avatar || '',
	username: userStore.userInfo?.username || '',
	openid: userStore.userInfo?.openid || ''
})

// 选择头像
const onChooseAvatar = e => {
	form.avatar = e.detail.avatarUrl
}

// 保存资料
const handleSave = async () => {
	try {
		if (!form.username.trim()) {
			uni.showToast({
				title: '请输入昵称',
				icon: 'none'
			})
			return
		}

		// 显示loading
		uni.showLoading({
			title: '保存中...',
			mask: true
		})

		console.log('form', form)

		// 如果头像不是OSS地址，则上传头像
		if (!form.avatar.startsWith('https://ciyu-edu')) {
			// 上传头像
			const uploadResult = await userApi.uploadAvatar(form.avatar)
			if (uploadResult.success) {
				// 更新头像地址为OSS地址
				form.avatar = uploadResult.data.url
			} else {
				throw new Error('头像上传失败')
			}
		}

		// 更新用户资料
		const result = await userStore.updateProfile({
			avatar: form.avatar,
			username: form.username,
			openid: form.openid
		})

		uni.hideLoading()

		console.log('更新用户信息：', result)

		if (result.success) {
			// 更新用户信息
			// userStore.userInfo = result.data.userInfo
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			})

			// 返回上一页
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	} catch (error) {
		uni.hideLoading()
		uni.showToast({
			title: error.message || '保存失败',
			icon: 'none'
		})
	}
}
</script>

<style lang="scss" scoped>
.edit-profile {
	padding: 32rpx;

	.form-item {
		display: flex;
		align-items: center;
		padding: 32rpx 0;
		border-bottom: 2rpx solid #eee;

		.label {
			width: 120rpx;
			font-size: 28rpx;
			color: #333;
		}

		.avatar-wrapper {
			padding: 0;
			width: 120rpx;
			height: 120rpx;
			background: none;

			&::after {
				border: none;
			}

			.avatar {
				width: 100%;
				height: 100%;
				border-radius: 16rpx;
			}
		}

		.input {
			flex: 1;
			height: 88rpx;
			font-size: 28rpx;
		}
	}

	.save-btn {
		margin-top: 60rpx;
		width: 100%;
		height: 88rpx;
		background: linear-gradient(90deg, #3bccdd 0%, #5b88e5 100%);
		border-radius: 44rpx;
		color: #fff;
		font-size: 32rpx;
		font-weight: 500;

		&::after {
			border: none;
		}
	}
}
</style>
